<template>
    <div>
        <el-card style="border:none !important;border-radius: 12px;box-shadow:none !important">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item :to="{ path: '/userhome' }">个人中心</el-breadcrumb-item>
                <el-breadcrumb-item>
                    <a href="/recharge_order">订单管理</a>
                </el-breadcrumb-item>
                <el-breadcrumb-item>充值订单</el-breadcrumb-item>
            </el-breadcrumb>
            <div class="tab-nav-bd">
                <span class="title">充值订单</span>
            </div>
        </el-card>
        <div style="margin-top: 20px;">
            <el-card style="border:none !important;border-radius: 12px;box-shadow:none !important">
                <!-- <div class="statusCss">状态:<el-radio-group v-model="radio1"  style="margin-left: 15px;">
                        <el-radio-button label="全部" value="New York" />
                        <el-radio-button label="已完成" value="Washington" />
                        <el-radio-button label="待支付" value="Los Angeles" />
                        <el-radio-button label="已取消" value="Chicago" />
                    </el-radio-group></div> -->
                <el-table :data="orderData" style="width: 100%" stripe>
                    <el-table-column prop="order_no" label="订单号" show-overflow-tooltip align="center" />
                    <el-table-column prop="create_time" label="时间" align="center" />
                    <el-table-column prop="remark" label="类型" align="center" />
                    <el-table-column label="实付金额" align="center">
                        <template #default="scope">
                            {{scope.row.pay_price || 0}}元
                        </template>
                    </el-table-column>
                    <el-table-column prop="status_text" label="订单状态" align="center">
                    </el-table-column>
                    <el-table-column label="操作" align="center">
                        <template #default="scope">
                            <el-text class="mx-1" v-if="scope.row.status == 2"
                                style="text-decoration: none;cursor: pointer;color: #e85623 !important;"
                                @click="cancelDelOrder(scope.row.id, 'del')">删除</el-text>
                            <el-text class="mx-1" v-else-if="scope.row.status == 1 && scope.row.invoice_status == 0"
                                style="text-decoration: none;cursor: pointer; color: #e85623 !important;" 
                                @click="applyForInvoicing(scope.row, 'apply')">申请开票</el-text>
                            <el-text class="mx-1" v-else-if="scope.row.status == 1 && scope.row.invoice_status == 1"
                                style="text-decoration: none;cursor: pointer; color: #e85623 !important;"
                                @click="applyForInvoicing(scope.row, 'inspect')">查看开票</el-text>
                            <el-text class="mx-1" v-else-if="scope.row.status == 1 && scope.row.invoice_status == 2"
                                style="text-decoration: none;cursor: pointer; color: #e85623 !important;"
                                @click="applyForInvoicing(scope.row, 'wait')">申请中...</el-text>
                            <el-text class="mx-1" v-else style="text-decoration: none;cursor: pointer;color: #e85623 !important;"
                                @click="cancelDelOrder(scope.row, 'cancel')">取消</el-text>
                        </template>
                    </el-table-column>
                </el-table>
                <div style="margin-top: 20px;display: flex;align-items: center;justify-content: center; width: 100%;">
                    <el-pagination background v-model:current-page="currentPage" v-model:page-size="pageSize"
                        layout="prev, pager, next" :total="total" @current-change="handleCurrentChange"
                        :hide-on-single-page="true" />
                </div>
            </el-card>
        </div>


        <el-dialog class="invoice-dialog" v-model="invoiceDialogVisible" :close-on-press-escape="false" title="开票申请"
            :close-on-click-modal="false" append-to-body align-center style="border-radius: 16px !important;"
            @close="invoiceCloseDialog">
            <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="auto" class="demo-ruleForm" status-icon>
                <el-form-item label="开票金额">
                    <el-text class="mx-1" type="danger"> {{ruleForm.price || 0}}元</el-text>
                   
                </el-form-item>
                <el-form-item label="发票类型" prop="invoice_type">
                    <el-radio-group v-model="ruleForm.invoice_type">
                        <el-radio value="1">普通发票</el-radio>
                        <el-radio value="2">专用发票</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="抬头类型" prop="invoice_header_type">
                    <el-radio-group v-model="ruleForm.invoice_header_type" >
                        <el-radio value="1">企业</el-radio>
                        <el-radio value="2">个人</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="发票抬头" prop="invoice_header">
                    <el-input v-model="ruleForm.invoice_header" />
                </el-form-item>
                <el-form-item label="纳税人识别号" prop="invoice_tax_no" v-if="ruleForm.invoice_header_type == '1'">
                    <el-input v-model="ruleForm.invoice_tax_no" @keyup="handleKeyUp" />
                </el-form-item>
                <el-form-item label="发票内容" prop="invoice_service">
                    <el-radio-group v-model="ruleForm.invoice_service">
                        <el-radio value="1">信息技术服务*云素材服务费</el-radio>
                        <el-radio value="2">信息技术服务*技术服务费</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="发送邮箱" prop="email">
                    <el-input v-model="ruleForm.email" />
                </el-form-item>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="invoiceDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="saveApplyInvoice(ruleFormRef)">
                        提交申请
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, reactive } from 'vue';
import type { FormInstance, FormRules } from 'element-plus'
import { orderList, cancelAndOrder,applyInvoice } from '../../api/order/index'
import { ElMessage, ElMessageBox } from 'element-plus'
const currentPage = ref(1); //当前页
const pageSize = ref(10) //每页显示条目个数
const total = ref(0)
const invoiceDialogVisible = ref(false)

const validateEmail = (rule:any, value:any, callback:any) => {
      const emailRegex = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
      if (!emailRegex.test(value)) {
        callback(new Error('请输入正确的邮箱地址'));
      } else {
        callback();
      }
    };
//申请发票的字段规则
interface RuleForm {
    order_id:string,
    price: string,
    invoice_type: string,
    invoice_header_type: string,
    invoice_header:string,
    invoice_tax_no:string,
    invoice_service:string,
    email:string
}
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
    order_id:'',
    price:'',
    invoice_type: '',
    invoice_header_type: '1',
    invoice_header:'',
    invoice_tax_no:'',
    invoice_service:'1',
    email:''
})
//表单验证规则
const rules = reactive<FormRules<RuleForm>>({
    invoice_type: [
        {
            required: true,
            message: '请选择发票类型',
            trigger: 'change',
        },
    ],
    invoice_header_type: [
        {
            required: true,
            message: '请选择抬头类型',
            trigger: 'change',
        },
    ],
    invoice_header: [
        { required: true, message: '请输入发票抬头', trigger: 'blur' },
        { min: 3, max: 20, message: '发票抬头长度3-20个字符', trigger: 'blur' },
    ],
    invoice_tax_no: [
        { required: true, message: '请输入发票抬头纳税人识别号', trigger: 'blur' }
    ],
    invoice_service: [
        {
            required: true,
            message: '请输入发票内容',
            trigger: 'change',
        },
    ],
    email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { validator: validateEmail, trigger: 'blur' },
    ],
})

//验证营业执照号码的规则
const handleKeyUp = () =>{
    // 使用正则表达式替换非字母数字、非点和非斜杠的字符  
    ruleForm.invoice_tax_no = ruleForm.invoice_tax_no.replace(/[^\w\.\/]/ig, '');  
}
//申请开票提交
const saveApplyInvoice = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
        applyInvoice({ruleForm}).then((res:any)=>{
            if(res.code == 1){
                balanceInfo()
                ElMessage({
                        type: 'success',
                        message: '申请中...',
                    })
                    formEl.resetFields() //清空
                invoiceDialogVisible.value = false
            }
        }).catch((err:any)=>{
            console.log(err)
        })
    } else {
      console.log('error submit!', fields)
    }
   
  })
}

//数据源
const orderData = ref<any>([]);
const balanceInfo = () => {
    orderList({ limit: pageSize.value, page: currentPage.value }).then((res: any) => {
        if (res.code == 1) {
            orderData.value = res.data.list
            total.value = res.data.total
        }
    }).catch((error: any) => {
        if (error.code == 0) {
            console.log("余额获取失败")
        }
    })
}
//选择页数
const handleCurrentChange = (val: number) => {
    currentPage.value = val
    balanceInfo()
}
//删除OR取消订单
const cancelDelOrder = (id: number, option_type: string) => {
    ElMessageBox.confirm(
        '确认操作当前的订单记录？',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            confirmButtonClass: 'confirmButtonCss',
            type: 'error',
        }
    )
        .then(() => {
            cancelAndOrder({ order_id: id, option_type: option_type }).then((res: any) => {
                if (res.code == 1) {
                    ElMessage({
                        type: 'success',
                        message: '操作成功',
                    })
                    balanceInfo()
                }
            }).catch((err: any) => {
                console.log(err)
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消当前操作',
            })
        })
}

//申请开票
const applyForInvoicing = (item: any, option: string) => {
    if (option == 'wait') {
        ElMessageBox.alert('您的开票申请正在处理中。工作日48小时内审核，周末延时审核处理。', '开票提示', {
            // if you want to disable its autofocus
            // autofocus: false,
            confirmButtonText: '好的',
        })
    }
    if (option == 'apply') { //申请开票
        ruleForm.order_id = item.id
        ruleForm.price = item.pay_price
        invoiceDialogVisible.value = true
    }
    if(option == 'inspect'){
        //提示
        ElMessageBox.alert('您的发票已发送至您的邮箱:'+item.invoice.email+',请注意查收~如有疑问可联系客服咨询。', '开票提示', {
            // if you want to disable its autofocus
            // autofocus: false,
            confirmButtonText: '好的',
        })
    }

}


//关闭发票窗口
const invoiceCloseDialog = () => {
    console.log(123)
}


onMounted(() => {
    balanceInfo()
})



</script>
<style>
.confirmButtonCss {
    background-color: red !important;
    border-color: red !important;
}
</style>
<style scoped>
.tab-nav-bd {
    margin-top: 16px;
}

.tab-nav-bd .title {
    font-size: 18px;
    font-weight: 700;
    color: #1D2129;
    line-height: 26px;
}

.statusCss {
    height: 70px;
    font-size: 16px;
    white-space: nowrap;
    display: flex;
    justify-content: flex-start;
    align-items: center;
}
</style>